function [label image] = bestMatch(qInd,testImgs,testLbls,useMin,D,dOpt)
%Returns the best match for the given image and test data
%
%qInd is the index into testImgs for the query image
%
%testImgs is a 28x28xn matrix containing images to test against
%
%testLbls is a 1xn vector containing the corresponding labels
%
%useMin is a boolean specifying if min or max should be used to find the
%match
%
%D is a handle to the distance function to be used
%
%dOpt is a third parameter to pass to D

n=size(testImgs,3);

qImg=testImgs(:,:,qInd);

q=qImg(:);

dists=zeros(1,n);

for i=1:n
    tImg=testImgs(:,:,i);
    dists(i) = D(q,tImg(:),dOpt);
end

if(useMin)
    %exclude self matches
    dists(qInd)=Inf;
    
    %find min 
    [~, I] = min(dists);
else
    %exclude self matches
    dists(qInd)=-Inf;
    
    %find max
    [~, I] = max(dists);
end

label = testLbls(I(1));
image = testImgs(:,:,I(1));

end
